package com.simple.business.util;

import cn.hutool.core.date.DateUtil;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.simple.business.config.properties.QiNiuYunConfig;
import com.simple.common.constant.StrPool;
import com.simple.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @desc
 * @Author Simple
 * @Date 2025/3/14 22:08
 **/
@Slf4j
@Component
public class QiNiuYunUtil {

    @Resource
    private UploadManager uploadManager;
    @Resource
    private Auth auth;
    @Resource
    private QiNiuYunConfig qiNiuYunConfig;
    @Resource
    private BucketManager bucketManager;

    /**
     * 上传文件
     * @param file
     * @param fileName
     * @return
     * @throws QiniuException
     */
    public String uploadImg(FileInputStream file, String fileName) throws QiniuException {
        String token = auth.uploadToken(qiNiuYunConfig.getUriPrefix());
        fileName = qiNiuYunConfig.getFileNameFix() + File.separator + DateUtil.format(new Date(), "yyyyMMdd") + File.separator + fileName;
        Response res = uploadManager.put(file, fileName, token, null, null);
        if (!res.isOK()) {
            log.error("七牛云上传失败，原因：{}", res.error);
            return "";
        }
        return qiNiuYunConfig.getUriPrefix() + File.separator + fileName;
    }

    /**
     * 上传文件
     * @param img
     * @return
     */
    public String uploadImg(MultipartFile img) {
        String originalFilename = img.getOriginalFilename();
        if (originalFilename == null) {
            throw new ServiceException("文件名不能为空");
        }

        if (!checkImageSuffix(originalFilename)) {
            // throw new ServiceException(AppHttpCodeEnum.FILE_TYPE_ERROR.getMsg());
            throw new ServiceException("上传类型格式不为图片jpg,png...");
        }

        String fileName = originalFilename.substring(0, originalFilename.lastIndexOf("."))
                 + "-" + UUID.randomUUID().toString().replaceAll("-", "") +
                originalFilename.substring(originalFilename.lastIndexOf("."));
        String filePath =  qiNiuYunConfig.getFileNameFix() + StrPool.SLASH +
                DateUtil.format(new Date(), "yyyyMMdd") + StrPool.SLASH + "images" + StrPool.SLASH + fileName;

        log.info("七牛云生成fileType: " + filePath);
        String url = uploadOss(img, filePath);
        return url;
    }

    /**
     * 删除七牛云上的图片
     * @param key
     * @return
     * @throws QiniuException
     */
    public String deleteImg(String key) {
        try {
            // 由于bucketManager注入了spring,且初始化了a,skey,和地区,所以可以直接传bucket调用
            // 如果有重传需求则三次重传
            Response response = bucketManager.delete(qiNiuYunConfig.getBucketName(), key);
            int retry = 0;
            while (response.needRetry() && retry++ < 3) {
                response = bucketManager.delete(qiNiuYunConfig.getBucketName(), key);
            }
            return response.statusCode == 200 ? "删除成功!" : "删除失败!";
        } catch (Exception e) {
            log.error("删除七牛云图片异常: " + e.getMessage());
        }
        return "删除失败";
    }

    private String uploadOss(MultipartFile file, String filePath) {
        // 这里的getUploadToken()是获取上传凭证，由
        // Access Key: 访问密钥
        // Secret Key: 秘密密钥 和 存储空间名 bucket所生成
        // 同时还设置了令牌过期时间sxpire
        // 这两个密钥用于身份验证和权限控制，确保只有授权的用户可以访问或操作资源
        // 获取文件输入流
        try {
            // 将文件转为输入流，后面流给七牛云
            InputStream inputStream = file.getInputStream();
            //上传ing...
            Response response = uploadManager.put(inputStream, filePath, getUploadToken(), null, null);
            // 如果上一步执行没问题则说明上传完毕,此时给链接前端展示即可
            int retry = 0;
            // 如果有重传需求则三次重传
            while (response.needRetry() && retry < 3) {
                response = uploadManager.put(inputStream, filePath, getUploadToken(), null, null);
                retry++;
            }
            if (response.statusCode == 200) {
                return qiNiuYunConfig.getUriPrefix() + File.separator + filePath;
            }
            return "";

        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 获取上传凭证
     */
    private String getUploadToken() {
        return auth.uploadToken(qiNiuYunConfig.getBucketName(), null, 3600, null);
    }

    /**
     * 输入文件名，获取文件的后缀
     * @param fileName 文件名
     * @return 文件后缀
     */
    private String getFileSuffix(String fileName) {
        // 拆分文件和后缀
        String[] split = fileName.split("\\.");
        if (split.length <= 1) {
            return "";
        }
        return split[split.length - 1];
    }

    /**
     * 根据传入的后缀和文件类型，判断其后缀是否正常
     */
    private boolean checkImageSuffix(String originalFilename) {
        String fileSuffix = getFileSuffix(originalFilename);
        List<String> images = Arrays.asList("bmp，jpg，png，tif，gif，pcx，tga，exif，fpx，svg，psd，cdr，pcd，dxf，ufo，eps，ai，raw，WMF，webp，avif，apng".split("，"));
        return images.contains(fileSuffix);
    }


}


